import { IMyApp } from "../../../app"
import { IAddress} from "./IAddress";

// import Toast from "../../../miniprogram_npm/@vant/weapp/toast/toast";
const app = getApp<IMyApp>();

Page({
  data: {
    adds:[] as IAddress[],
    
  },
  loadAddressList(){
    let self = this;

    let url = app.globalData.apisite + '/appletapi/address/list';
    let appletid = app.globalData.appletid;
    let openid = app.globalData.openid;

    app.http.postRequest(url, "openid=" + openid + "&applet_id=" + appletid).then(json => {
      if(json.total>0){
        let rows: IAddress[] = [];

        for (var i = 0; i < json.data.length; i++){
          var one = json.data[i];
          var item : IAddress = {
            id: one.ADD_ID,
            name: one.ADD_NAME,
            address: one.ADD_ADDRESS,
            phone: one.ADD_PHONE,
          };
          rows.push(item);
        }

        this.setData({
          adds:rows
        });
      }
    });
  },
  onLoad() {
    this.loadAddressList();
  },
  addAddressBtnClicked(){
    let self = this;
    wx.navigateTo({
      url: '/pages/ucenter/address/address_addedit?action=add',
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage(data: any) {
          var rows = self.data.adds;
          rows.push(data.data);
          self.setData({
            adds: rows
          });
        }
      },
      success(res: any){
        // 通过eventChannel向被打开页面传送数据
        console.warn("通过eventChannel向被打开页面传送数据：");
        res.eventChannel.emit('acceptDataFromOpenerPage', { data: 'test' })
      }
    });
  },
  cellClick(e : any){
    let id = e.currentTarget.dataset.id;
    let self = this;
    wx.navigateTo({
      url: '/pages/ucenter/address/address_addedit?action=edit&id=' + id,
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage(data: any) {
          // reload data
          self.loadAddressList();
        }
      },
      success(res: any) {
        // 通过eventChannel向被打开页面传送数据
        // console.warn("通过eventChannel向被打开页面传送数据：");
        // res.eventChannel.emit('acceptDataFromOpenerPage', { data: 'test' })
      }
    });
  }

})